# -*- coding: utf-8 -*-
#
# Author:: hanjunfeng
# Date:: 2022/7/6

"""
昨日交易量排名
市值

"""
import os
from time import sleep

import tushare as ts

from config.private_config import ts_token_list
from submodules.common.lib.json_ import dict_to_json_file, json_file_to_dict

from submodules.common.lib import local_paths

from submodules.common.lib.datetime_ import get_date
from lib.common import ts_code_to_tx_code
from submodules.common.lib.log_ import get_logger

logger = get_logger()
today_date_del10 = get_date(-10)
today_date = get_date()
for token in ts_token_list:
    try:
        pro = ts.pro_api(token)
        pro.daily(ts_code="000001.SZ", start_date=today_date_del10, end_date=today_date)
        break
    except Exception as e:
        logger.error(repr(e))


def get_latest_date():
    today_date_del10 = get_date(-10)
    today_date = get_date()

    for i in range(300):
        try:
            data = pro.daily(
                ts_code="000001.SZ", start_date=today_date_del10, end_date=today_date
            )
            break
        except Exception as e:
            logger.info(repr(e))
            sleep(1)
    latest_data_date = data.at[0, "trade_date"]
    return latest_data_date


def get_stock_list():
    stock_list = {}

    for i in range(300):
        try:
            data = pro.stock_basic(
                exchange="",
                list_status="L",
                fields="ts_code,symbol,name,area,industry,list_date",
            )
            break
        except Exception as e:
            logger.info(repr(e))
            sleep(1)
    for i in range(len(data)):
        ts_code_tmp = data.at[i, "ts_code"]
        dict_tmp = {ts_code_tmp: {}}
        dict_tmp[ts_code_tmp].update({"ts_code": ts_code_tmp})
        dict_tmp[ts_code_tmp].update({"symbol": data.at[i, "symbol"]})
        dict_tmp[ts_code_tmp].update({"name": data.at[i, "name"]})
        dict_tmp[ts_code_tmp].update({"area": data.at[i, "area"]})
        dict_tmp[ts_code_tmp].update({"industry": data.at[i, "industry"]})
        dict_tmp[ts_code_tmp].update({"list_date": data.at[i, "list_date"]})
        stock_list.update(dict_tmp)
    # logger.info(stock_list)
    return stock_list


def get_code_list_tx(stock_list):
    # stock_list = get_stock_list()
    tx_code_list = []
    ts_code_list = [k for k, v in stock_list.items()]
    for ts_code in ts_code_list:
        ts_code_tx = ts_code_to_tx_code(ts_code)
        tx_code_list.append(ts_code_tx)
    return tx_code_list


# def get_amount_rank(stock_list, top_num=1000):
#     # stock_list = get_stock_list()
#     latest_date = get_latest_date()
#
#     amount_list = []
#
#     ts_code_list = [k for k, v in stock_list.items()]
#
#     for i in range(math.ceil(len(stock_list) / 1000)):
#         start = i * 1000
#         end = (i + 1) * 1000
#         ts_code_list_tmp = ts_code_list[start:end]
#
#         ts_code_all_list_tmp_str = ",".join(ts_code_list_tmp)
#         for i in range(300):
#             try:
#                 data = pro.daily(ts_code=ts_code_all_list_tmp_str, start_date=latest_data_date,
#                                  end_date=latest_data_date)
#                 break
#             except:
#                 sleep(1)
#
#         for i in range(len(data)):
#             dict_tmp = {}
#             ts_code = data.at[i, "ts_code"]
#             dict_tmp.update({"amount": data.at[i, "amount"]})
#             dict_tmp.update({"ts_code": ts_code})
#             dict_tmp.update({"name": stock_list[ts_code]["name"]})
#             dict_tmp.update({"industry": stock_list[ts_code]["industry"]})
#
#             amount_list.append(dict_tmp)
#     amount_list_sorted = sorted(amount_list, key=lambda x: x["amount"], reverse=True)
#
#     return amount_list_sorted[:top_num]


def get_market_info_all_tx_sorted(market_info_all_tx):
    market_info_all_tx_sorted = sorted(
        market_info_all_tx.items(), key=lambda x: float(x[1][44]), reverse=True
    )
    return market_info_all_tx_sorted


def get_candles_data(ts_code, limit=100, use_local_data=True):
    data_dir = os.path.join(local_paths.project_tmp_path, "data")
    latest_date = get_latest_date()
    data_path = os.path.join(data_dir, f"{latest_date}_{ts_code}.json")
    if use_local_data:
        if os.path.exists(data_dir):
            pass
        else:
            os.mkdir(data_dir)

        if os.path.exists(data_path):
            try:
                res = json_file_to_dict(data_path)
                logger.info(f"use local data, data_name:{ts_code}")
                return res
            except Exception as e:
                logger.error(f"data_path:{data_path}")
                logger.error(repr(e))

    start_date = get_date(offset=-int(limit))
    print(start_date)
    candles_data = []
    for i in range(300):
        try:
            data = pro.query(
                "daily", ts_code=ts_code, start_date=start_date, end_date=latest_date
            )
            logger.info(f"use online data, ts_code:{ts_code}")
            break
        except:
            sleep(1)

    for i in range(len(data) - 1):
        ts_code = data.at[i, "ts_code"]
        trade_date = data.at[i, "trade_date"]
        open = float(data.at[i, "open"])
        high = float(data.at[i, "high"])
        low = float(data.at[i, "low"])
        close = float(data.at[i, "close"])
        close_yesterday = float(data.at[i + 1, "close"])
        pre_close = data.at[i, "pre_close"]
        change = data.at[i, "change"]
        pct_chg = data.at[i, "pct_chg"]
        vol = data.at[i, "vol"]
        amount = data.at[i, "amount"]
        gains_percent = (close / close_yesterday - 1) * 100  # 涨幅 index=7
        amplitude_percent = (high / low - 1) * 100  # 振幅 index=8

        candles_data.append(
            [
                trade_date,
                open,
                high,
                low,
                close,
                vol,
                amount,
                gains_percent,
                amplitude_percent,
            ]
        )

    dict_to_json_file(candles_data, data_path)
    return candles_data


if __name__ == "__main__":
    # get_amount_rank()
    #
    # get_latest_date()

    # res = get_stock_list()
    # print(res)

    # res = get_amount_rank()
    # print(res)

    # stock_list = get_stock_list()
    # #
    # # print(stock_list)
    # market_info_all_tx = get_market_info_all_tx(stock_list)
    #
    # market_info_all_tx_sorted = get_market_info_all_tx_sorted(market_info_all_tx)
    #
    # count = 0
    # for item in market_info_all_tx_sorted:
    #     market_value = float(item[1][44])
    #     if 1000 > market_value > 50:
    #         count += 1
    #         print(item)
    #         print(market_value)
    # print(count)

    def test_get_latest_date():
        res = get_latest_date()
        print(res)


    def test_get_tx_code_list():
        stock_list = get_stock_list()
        res = get_code_list_tx(stock_list)
        print(res)


    def test_get_stock_list():
        res = get_stock_list()
        print(res)


    def test_get_candles_data():
        ts_code = "000001.SZ"
        # ts_code = "601330.SH"  # TODO  HS  SH
        # ts_code = "513060.SH"
        # res = get_candles_data(ts_code)
        res = get_candles_data(ts_code=ts_code, limit=1000, use_local_data=False)
        print(res)
        print(len(res))


    test_get_candles_data()
